package com.reggie.interceptor;
//Jwt令牌校验的拦截器

import com.reggie.annotation.IgnoreToken;
import com.reggie.constant.JwtClaimsConstant;
import com.reggie.context.BaseContext;
import com.reggie.properties.JwtProperties;
import com.reggie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到的请求:{}"+request.getRequestURI());
        //拦截之前判断 获取到的是Controller的方法 还是其他资源
        if(!(handler instanceof HandlerMethod)) {
            //当前拦截的不是动态方法的直接放行
            return true;
        }

        //获取当前被拦截的方法上是否存在IgnoreToken的注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        boolean has = handlerMethod.hasMethodAnnotation(IgnoreToken.class);
        if (has){
            return true;
        }

        //从请求头获取JWT令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try {
            //解析 Jwt令牌
            /**
             * JwtUtil.parseJWT 调用 工具类的解析方法parseJwt
             */
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);

            //获取当前登录的员工id
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            //保存当前登录的员工Id到线程本地变量
            BaseContext.setCurrentId(empId);


            return true;
        } catch (Exception e) {
            log.error("jwt令牌解析失败");
            //401代表用户没有访问权限 需要进行身份认证
            response.setStatus(401);
            return false;

        }


    }
}
